package com.weijianhuawen.wjblog.admin.event.subscriber;

import com.sun.org.apache.xpath.internal.operations.Bool;
import com.weijianhuawen.wjblog.admin.event.PublishCommentEvent;
import com.weijianhuawen.wjblog.common.domain.dos.BlogSettingsDo;
import com.weijianhuawen.wjblog.common.domain.dos.CommentDo;
import com.weijianhuawen.wjblog.common.domain.mapper.BlogSettingsMapper;
import com.weijianhuawen.wjblog.common.domain.mapper.CommentMapper;
import com.weijianhuawen.wjblog.common.enums.CommentStatusEnum;
import com.weijianhuawen.wjblog.common.exception.BizException;
import com.weijianhuawen.wjblog.common.mail.MailHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description: 评论发布事件订阅者
 * @date: 2024-12-09 22:33
 */

@Component
@Slf4j
public class PublishCommentSubscriber implements ApplicationListener<PublishCommentEvent> {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private BlogSettingsMapper blogSettingsMapper;
    @Autowired
    private MailHelper mailHelper;
    @Value("${blog.base.url}")
    private String baseUrl;
    @Value("${blog.base.path}")
    private String basePath;

    @Override
    @Async("threadPoolTaskExecutor")
    public void onApplicationEvent(PublishCommentEvent event) {
        // 获取评论id
        Long commentId  = event.getCommentId();
        // 获取当前执行线程名称
        String threadName =  Thread.currentThread().getName();

        log.info("【发布评论事件订阅者】 处理任务线程名：{}", threadName);
        log.info("【发布评论事件订阅者】 开始消费事件！, 评论id：{}", commentId);

        // 获取评论信息
        CommentDo commentDo = commentMapper.selectById(commentId);
        if (Objects.isNull(commentDo)) {
            // 评论不存在
            log.warn("【发布评论事件订阅者】 评论id：{}， 不存在于数据库中，请检查！", commentId);
            log.warn("【发布评论事件订阅者】 事件消费遇到异常！！！");
            return;
        }

        // 获取评论相关信息
        Long replyCommentId = commentDo.getReplyCommentId();
        String nickName = commentDo.getNickname();
        String content = commentDo.getContent();
        Integer status = commentDo.getStatus();

        // 获取博客设置相关信息
        BlogSettingsDo blogSettingsDo = blogSettingsMapper.selectById(1L);
        // 博客名称
        String blogName = blogSettingsDo.getBlogName();
        // 博主邮箱
        String authMail = blogSettingsDo.getMail();
        // 是否需要审核
        Boolean isCommentExamineOpen = blogSettingsDo.getIsCommentExamineOpen();
        // 是否开启敏感词过滤
        Boolean isSensiWordOpen = blogSettingsDo.getIsCommentSensiWordOpen();
        // 博客访问地址
        String domain = "http://" + baseUrl + basePath;

        // 二级评论，如果评论状态为正常，则发送邮件给被评论人
        if (Objects.nonNull(replyCommentId) && Objects.equals(status, CommentStatusEnum.NORMAL.getCode())) {
            CommentDo replyCommentDo = commentMapper.selectById(replyCommentId);

            String to = replyCommentDo.getMail();
            String routerUrl = replyCommentDo.getRouterUrl();
            String subject = String.format("【未见花闻博客平台】 您在%s的评论收到了回复", blogName);

            // 构建Html
            String html = String.format("<html><body>" +
                    "<h2>你的评论:</h2><p>%s，收到了回复</p>" +
                    "<h2>%s 回复了你:</h2><p>%s</p>"  +
                    "<p><a href='%s%s' target='_blank'>查看详情</a></p>" +
                    "</body></html>", replyCommentDo.getContent(), nickName, content, domain, routerUrl);

            // 发送邮件
            mailHelper.sendHtml(to, subject, html);
        } else if (Objects.isNull(replyCommentId) && StringUtils.isNotBlank(authMail)){
            // 获取评论路由
            String routerUrl = commentDo.getRouterUrl();
            // 编辑主题
            String subject = String.format("【未见花闻博客平台】 您收到了来自%s的评论", blogName);

            // 如果评论状态为审核中，则在主题后面加一个审核中的字样
            if (isCommentExamineOpen && Objects.equals(status, CommentStatusEnum.WAIT_EXAMINE.getCode())) {
                subject += "[待审核]";
            }
            // 如果开启了敏感词过滤，系统检测到敏感词，则在主题后面加一个系统拦截字样
            if (isSensiWordOpen && Objects.equals(status, CommentStatusEnum.EXAMINE_FAILED.getCode())) {
                subject += "[系统已拦截]";
            }

            // 构建Html
            String html = String.format("<html><body>" +
                    "<h2>博客页面：</h2><p>%s%s</p>" +
                    "<h2>%s 回复了你:</h2><p>%s</p>"  +
                    "<p><a href='%s%s' target='_blank'>查看详情</a></p>" +
                    "</body></html>", domain, routerUrl, nickName, content, domain, routerUrl);

            // 发送邮件
            mailHelper.sendHtml(authMail, subject, html);
        }

    }
}
